package com.yyuap.summer.core;

import android.text.TextUtils;
import android.util.Log;

import com.yonyou.uap.um.service.ServiceCallback;

import org.apache.cordova.CordovaPlugin;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;

public class IUAPServiceCallback
        implements ServiceCallback {
    private WeakReference<CordovaPlugin> mCordova = null;
    private JSONObject mParameter = null;
    CordovaPlugin cordova;

    public IUAPServiceCallback(CordovaPlugin cordova, String method, JSONObject params) {
        this.mCordova = new WeakReference(cordova);
        this.mParameter = params;
        this.cordova = cordova;
    }

    public void execute(JSONObject response) {
        String callback = this.mParameter.optString("callback", "");
        response.remove("callback_object");
        response.remove("callback");
        if ((!TextUtils.isEmpty(callback)) &&
                (this.mCordova.get() != null)) {
            callback = callback.replace("()", "(" + response.toString().replace("'", "") + ")");
            Log.d("yyy", "execute callback  : " + callback);
            final String mCallback = callback;
            this.cordova.cordova.getActivity().runOnUiThread(new Runnable() {
                public void run() {
//                    ((CordovaPlugin) IUAPServiceCallback.this.mCordova.get()).webView.loadUrl("javascript:try{" + mCallback + "}catch(e){alert(e)}");
                    ((CordovaPlugin) IUAPServiceCallback.this.mCordova.get()).webView.loadUrl("javascript:try{" + mCallback + "}catch(e){}");
                }
            });
        }
    }


    public static String messageInfo = "";
    /**
     * 校验是否通过
     * @param response
     * @return 校验是否通过
     */
    public boolean checkCallBackMessage(JSONObject response){

        try{
            // h5报错提示
            String result = response.optString("result","{}");
            JSONObject jsonObject = new JSONObject(result);
            String msg = jsonObject.optString("msg","");
            if (!TextUtils.isEmpty(msg)){
                if(msg.contains("response code: 500")){

                    // 需要提示的信息
                    messageInfo = "";
                    
                    return false;
                }
            }
            return true;
        }catch (Exception e){
            LogUtils.e(e);
        }
        return true;

    }

    public void error(String code, String message) {
        String callback = this.mParameter.optString("error", "");
        if ((!TextUtils.isEmpty(callback)) &&
                (this.mCordova.get() != null)) {
            callback = callback.replace("()", "({'err_msg':'" + message + "'})");

            ((CordovaPlugin) this.mCordova.get()).webView.loadUrl("javascript:try{" + callback + "}catch(e){alert(e)}");

        }
    }
}
